package com.siyoumi.app.sys.service;

import com.siyoumi.app.entity.SysUser;
import com.siyoumi.app.entity.WxUser;
import com.siyoumi.app.entity.WxUserInfo;
import com.siyoumi.app.entity.WxUserLogin;
import com.siyoumi.app.modules.user.service.SvcSysUser;
import com.siyoumi.app.service.WxUserLoginService;
import com.siyoumi.app.service.WxUserService;
import com.siyoumi.app.sys.entity.GetTokenData;
import com.siyoumi.app.sys.service.impl.WxAppServiceImpl;
import com.siyoumi.app.sys.service.impl.WxServiceImpl;
import com.siyoumi.app.sys.vo.LoginVo;
import com.siyoumi.app.sys.vo.PhoneLoginVo;
import com.siyoumi.app.sys.vo.VaWxUser;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XJwt;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import org.apache.commons.collections4.map.LinkedMap;

//微信api
public interface WxApiService {
    static WxApiService getBean() {
        return getBean("wx_app");
    }

    static WxApiService getBean(String type) {
        WxApiService app = null;
        switch (type) {
            case "wx":
                app = XSpringContext.getBean(WxServiceImpl.class);
                break;
            case "wx_app":
                app = XSpringContext.getBean(WxAppServiceImpl.class);
                break;
        }

        return app;
    }

    default XReturn loginReturnData(GetTokenData tokenData) {
        SysAccsuperConfig entityConfig = SysAccsuperConfigService.getBean().getXConfig(tokenData.getX(), true);

        String token = getToken(tokenData);

        //前端返回参数
        XReturn r = XReturn.getR(0);

        r.setData("x", tokenData.getX());
        r.setData("uid", tokenData.getUid()); //空：未登陆
        r.setData("openid", tokenData.getOpenid());
        r.setData("token", token);
        if (XStr.hasAnyText(tokenData.getOpenid())) {
            WxUser entityWxUser = WxUserService.getBean().getByOpenid(tokenData.getOpenid());
            if (entityWxUser != null) {
                r.setData("wxuser_nickName", XStr.isNullOrEmpty(entityWxUser.getWxuser_nickname()) ? "" : entityWxUser.getWxuser_nickname());
                r.setData("wxuser_headimgurl", entityWxUser.getWxuser_headimgurl());
            }
        }

        LinkedMap<String, Object> mapAppend = new LinkedMap();
        mapAppend.put("fun_name", entityConfig.getAconfig_fun_name());
        mapAppend.put("img_root", SysConfig.getIns().getImgRoot());
        mapAppend.put("test", entityConfig.getAconfig_test());
        mapAppend.put("v", XDate.toMs() / 60);

        mapAppend.put("reset_oauth", false);
        r.setData("append_data", mapAppend);

        return r;
    }

    /**
     * 登陆成功统一返回参数
     *
     * @param entityWxUser
     * @param entityConfig
     */
    default XReturn loginReturnDataWx(WxUser entityWxUser, SysAccsuperConfig entityConfig) {
        GetTokenData data = GetTokenData.of("", entityConfig.getX(), entityWxUser.getWxuser_openid());
        WxUserLogin entityLogin = SvcSysUser.getBean().getLogin(entityWxUser.getWxuser_openid());
        Boolean isPhoneLogin = SvcSysUser.getBean().isLogin(entityLogin);
        if (isPhoneLogin) {
            //已登陆
            data.setUid(entityLogin.getWulogin_uid());
        }
        return loginReturnData(data);
        ////获取签名
        //XReturn tokenData = XReturn.getR(0);
        //tokenData.setData("timestamp", XDate.toMs());
        //tokenData.setData("x", entityConfig.getKey());
        //tokenData.setData("openid", entityWxUser.getWxuser_openid());
        //
        //tokenData.setData("uid", null);
        //WxUserLogin entityLogin = SvcSysUser.getBean().getLogin(entityWxUser.getWxuser_openid());
        //Boolean isPhoneLogin = SvcSysUser.getBean().isLogin(entityLogin);
        //if (isPhoneLogin) {
        //    //已登陆
        //    tokenData.setData("uid", entityLogin.getWulogin_uid());
        //}
        //String token = getToken(tokenData);
        //
        ////前端返回参数
        //XReturn r = XReturn.getR(0);
        //
        //r.setData("wxuser_nickName", XStr.isNullOrEmpty(entityWxUser.getWxuser_nickname()) ? "" : entityWxUser.getWxuser_nickname());
        //r.setData("wxuser_headimgurl", entityWxUser.getWxuser_headimgurl());
        //r.setData("wxuser_true_name", entityWxUser.getWxuser_true_name());
        //r.setData("wxuser_phone", entityWxUser.getWxuser_phone());
        //r.setData("openid", entityWxUser.getWxuser_openid());
        //r.setData("x", entityWxUser.getX());
        //r.setData("token", token);
        //r.setData("phone_login", isPhoneLogin);
        //
        //LinkedMap<String, Object> mapAppend = new LinkedMap();
        //mapAppend.put("fun_name", entityConfig.getAconfig_fun_name());
        //mapAppend.put("img_root", SysConfig.getIns().getImgRoot());
        //mapAppend.put("test", entityConfig.getAconfig_test());
        //mapAppend.put("v", XDate.toMs() / 60);
        //
        //// 15天重新授权
        //Boolean resetOauth = true;
        //if (entityWxUser.getWxuser_user_data_update_date() != null) {
        //    resetOauth = XDate.now().isAfter(entityWxUser.getWxuser_user_data_update_date().plusDays(30));
        //}
        //if (XStr.isNullOrEmpty(entityWxUser.getWxuser_headimgurl())) {
        //    resetOauth = true;
        //}
        //mapAppend.put("reset_oauth", resetOauth);
        //r.setData("append_data", mapAppend);
        //
        //return r;
    }

    /**
     * 登陆
     *
     * @param data
     */
    XReturn login(LoginVo data);


    /**
     * 手机登陆
     *
     * @param vo
     */
    default XReturn phoneLogin(PhoneLoginVo vo) {
        XValidator.checkTransaction();

        if (XStr.isNullOrEmpty(vo.getOpenid()) && XStr.isNullOrEmpty(vo.getUkey())) {
            return EnumSys.ERR_VAL.getR("缺少登陆密码");
        }

        SysUser entityUser = SvcSysUser.getBean().getUserByPhone(vo.getPhone());
        if (entityUser == null) {
            return EnumSys.ERR_VAL.getR("手机号未注册");
        }
        XValidator.err(SvcSysUser.getBean().valid(entityUser));

        if (XStr.hasAnyText(vo.getOpenid())) {
            WxUserLogin entitylogin = SvcSysUser.getBean().getLogin(vo.getOpenid());
            boolean updateLogin = true;
            if (entitylogin != null) {
                if (entitylogin.getWulogin_state() == 1 && entitylogin.getWulogin_uid().equals(entityUser.getUser_id())) {
                    //手机号登陆中，无需更新
                    updateLogin = false;
                }
            }

            if (updateLogin) {
                SvcSysUser.getBean().updateLoginState0(vo.getOpenid());

                WxUserLogin entityLoginUpdate = new WxUserLogin();
                entityLoginUpdate.setWulogin_uid(entityUser.getUser_id());
                entityLoginUpdate.setWulogin_x_id(XHttpContext.getX());
                entityLoginUpdate.setWulogin_openid(vo.getOpenid());
                entityLoginUpdate.setWulogin_state(1);
                entityLoginUpdate.setWulogin_state_date(XDate.now());
                WxUserLoginService.getBean().saveOrUpdatePassEqualField(entitylogin, entityLoginUpdate);
            }
        } else {
            String encPwd = XApp.encPwd(entityUser.getUser_x_id(), vo.getDecPwd());
            if (!entityUser.getUser_pwd().equals(encPwd)) {
                return EnumSys.PWD_ERR.getR("登陆密码错误");
            }
        }

        GetTokenData data = GetTokenData.of(entityUser.getUser_id(), XHttpContext.getX(), vo.getOpenid());
        return loginReturnData(data);
    }

    /**
     * 退出登陆
     *
     * @param openid
     */
    default XReturn phoneLogout(String openid) {
        SvcSysUser.getBean().updateLoginState0(openid);

        return EnumSys.OK.getR();
    }

    /**
     * 扫码登陆设置openid
     */
    XReturn loginSetOpenid(String token);

    /**
     * 获取手机号
     *
     * @param data
     */
    XReturn getPhone(String data);

    /**
     * 修改用户信息
     */
    XReturn userEdit(WxUserInfo entityWxUserInfo);

    /**
     * 修改用户信息
     */
    XReturn userUpdate(VaWxUser vo);

    /**
     * 我的地址
     */
    XReturn addressList(InputData inputData);


    default String getToken(GetTokenData data) {
        XReturn tokenData = XReturn.getR(0);
        tokenData.setData("timestamp", data.getTimestamp());
        tokenData.setData("x", data.getX());
        tokenData.setData("uid", data.getUid());
        tokenData.setData("openid", data.getOpenid());

        XJwt jwt = XJwt.getBean();
        return jwt.getToken(tokenData, data.getExpireSecond());
    }

    /**
     * 登陆成功获取token
     * 请求需要携带
     *
     * @return token
     */
    default String getToken(XReturn r) {
        Integer expireSecond = 3600 * 6;
        XJwt jwt = XJwt.getBean();

        return jwt.getToken(r, expireSecond);
    }
}
